package cn.com.b2office.dao.hibernate;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import cn.com.b2office.dao.CategoryDao;
import cn.com.b2office.domain.Category;

public class CategoryDaoHibernateImpl extends HibernateDaoSupport implements
		CategoryDao {

	private static final Log logger = LogFactory
			.getLog(CategoryDaoHibernateImpl.class);

	public String createCategory(Category category) {
		return (String) getHibernateTemplate().save(category);
	}

	public Category getCategory(String categoryId) {
		return (Category) getHibernateTemplate()
				.get(Category.class, categoryId);
	}

	public Category getParentCategory(String categoryId) {
		if (categoryId == null || categoryId.trim().equals("")
				|| categoryId.trim().length() == 2)
			return null;
		String parentCategoryId = categoryId.substring(0, 2);
		return (Category) getHibernateTemplate().get(Category.class,
				parentCategoryId);
	}

	@SuppressWarnings("unchecked")
	public List<Category> listAllCategories() {
		return getHibernateTemplate().find(
				"from Category where item_flag=0 order by item_clsno asc");
	}

	/**
	 * 列出该子类的直接父类及父类的父类(如果存在的话)
	 */
	public List<Category> listAncestries(String categoryId) {
		if (categoryId == null)
			return null;
		List<Category> list = new ArrayList<Category>();
		Session s = getSession();
		try {
			// 三级类
			if (categoryId.trim().length() == 6) {
				String firstId = categoryId.substring(0, 2);
				Category firstCategory = (Category) s.get(Category.class,
						firstId);
				String seondId = categoryId.substring(0, 4);
				Category secondCategory = (Category) s.get(Category.class,
						seondId);
				list.add(firstCategory);
				list.add(secondCategory);
			} else if (categoryId.trim().length() == 4) {
				String firstId = categoryId.substring(0, 2);
				Category firstCategory = (Category) s.get(Category.class,
						firstId);
				list.add(firstCategory);
			} else if (categoryId.trim().length() == 2) {
				// do nothing
			}
		} catch (RuntimeException e) {
			logger.error(e.getMessage());
			throw e;
		} finally {
			releaseSession(s);
		}
		return list;
	}

	/** 按照顺序列出所有的一级二级分类 */
	@SuppressWarnings("unchecked")
	public List<Category> listCascadeCategories() {
		List<Category> list = null;
		Session s = getSession();
		try {
			String hql = "from Category where item_flag=0 and notshow=0 and length(item_clsno)<=4 order by item_clsno asc";
			Query query = s.createQuery(hql);
			query.setCacheable(true);
			list = query.list();

		} catch (RuntimeException e) {
			logger.error(e.getMessage());
			throw e;
		} finally {
			releaseSession(s);
		}
		return list;
	}

	public void removeCategory(String categoryId) {
		Category category = (Category) getHibernateTemplate().get(
				Category.class, categoryId);
		if (category != null)
			getHibernateTemplate().delete(category);
	}

	public void removeCategory(Category category) {
		getHibernateTemplate().delete(category);
	}

	public void updateCategory(Category category) {
		// TODO 子类的更新的时候父类也要更新，写在service层还是dao层?
		getHibernateTemplate().update(category);
	}

	public List<Category> findAllChilds(String parentCategoryId) {
		List<Category> list = null;
		int len = parentCategoryId.trim().length();
		try {
			Session s = getSession();
			String hql = "from Category where item_flag=0 and item_clsno like '"
					+ parentCategoryId
					+ "%' and length(item_clsno)>"
					+ len
					+ " order by item_clsno asc";
			Query query = s.createQuery(hql);
			query.setCacheable(true);
			list = query.list();
			releaseSession(s);
		} catch (RuntimeException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		return list;
	}

	public List<Category> findDirectChilds(String parentCategoryId) {
		List<Category> list = null;
		int len = parentCategoryId.trim().length();
		Session s = getSession();
		try {
			String hql = "from Category where item_flag=0 and item_clsno like '"
					+ parentCategoryId
					+ "%' and length(item_clsno)="
					+ (len + 2) + " order by item_clsno asc";
			Query query = s.createQuery(hql);
			query.setCacheable(true);
			list = query.list();
			releaseSession(s);
		} catch (RuntimeException e) {
			logger.error(e.getMessage());
			throw e;
		} finally {
			releaseSession(s);
		}
		return list;
	}

	public List<Category> findTopLevelCategories() {
		List<Category> list = null;
		Session s = getSession();
		try {
			String hql = "from Category where item_flag=0 and notshow=0 and length(item_clsno)=2 order by sortwt desc";
			Query query = s.createQuery(hql);
			query.setCacheable(true);
			list = query.list();
		} catch (RuntimeException e) {
			logger.error(e.getMessage());
			throw e;
		} finally {
			releaseSession(s);
		}
		return list;
	}

}
